# -*- coding: utf-8 -*-
from flask import request
from urllib3.util import parse_url
from flask_restful import Resource, reqparse
import requests, json
from app import app_
api_log = app_.logger


class RequestCommit(Resource):
    # -----公共请求接口----
    """"""

    def __init__(self):
        self.reqparse = reqparse.RequestParser(trim=True)
        self.reqparse.add_argument('token', default='', location='args')
        self.reqparse.add_argument('request_url', required=True)
        self.reqparse.add_argument('requests_type', default='data', help='data, json')
        self.reqparse.add_argument('token_type', type=int, default=0, help='0.不是用客户端token,1.启用客户端token')

        self.reqparse.add_argument('headers', default='{}')
        # self.reqparse.add_argument('*')
        super(RequestCommit, self).__init__()

    def get_headers(self, headers):
        try:
            headers = json.loads(headers)
        except Exception as e:
            headers = {}
        return headers

    def options(self):
        return {}

    def get(self):

        args = self.reqparse.parse_args()
        token = args['token']
        token_type = args['token_type']
        request_url = args['request_url']
        requests_type = args['requests_type']
        headers = self.get_headers(args['headers'])
        request_dicts = request.values.dicts[0]
        params = dict(
            filter(lambda x: x[1] not in ['token', 'requests_type', 'request_url', 'headers'], request_dicts.items()))
        if token_type == 1 and '{token}' in request_url:
            client_token = '1'
            request_url.format(token=client_token)
        response = requests.get(url=request_url, headers=headers, params=params, verify=False)
        try:
            return response.json()
        except:
            return {"error_data": response.content}

    def post(self):
        args = self.reqparse.parse_args()
        token = args['token']
        token_type = args['token_type']
        request_url = args['request_url']
        parse_request_url_ = parse_url(request_url)
        requests_type = args['requests_type']
        headers = self.get_headers(args['headers'])
        request_dicts = request.values.dicts[1]
        data = dict(filter(lambda x: x[1] not in ['requests_type', 'request_url', 'headers'], request_dicts.items()))
        if token_type == 1 and '{token}' in request_url:
            client_token = '1'
            request_url.format(token=client_token)

        if requests_type == 'json':
            response = requests.post(url=request_url, headers=headers, json=data, verify=False)
        else:
            response = requests.post(url=request_url, headers=headers, data=data, verify=False)
        try:
            return response.json()
        except:
            return {"error_data": response.content}

